#include "modbushandler.h"
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QJsonDocument>
#include <QDebug>

ModbusHandler::ModbusHandler(QObject *parent) : QObject(parent)
{

}

int ModbusHandler::OperatePointType(int index)
{
    int type = 2;

    switch (index) {
    case 0:
        type = 0;
        break;
    case 1:
        type = 1;
        break;
    case 2:
        type = 2;
        break;
    case 3:
        type = 3;
        break;
    case 4:
        type = 4;
        break;
    case 5:
        type = 7;
        break;
    case 6:
        type = 8;
        break;
    default:
        type = 2;
        break;
    }

    return type;
}

QString ModbusHandler::OperatePointCoefficient(int index)
{
    QString coefficient = "0,1,0";

    switch (index) {
    case 0:
        coefficient = "0,1,0";
        break;
    case 1:
        coefficient = "0,0.1,0";
        break;
    case 2:
        coefficient = "0,0.01,0";
        break;
    case 3:
        coefficient = "0,10,0";
        break;
    case 4:
        coefficient = "0,100,0";
        break;
    default:
        coefficient = "0,1,0";
        break;
    }

    return coefficient;
}

void ModbusHandler::handleJsonData(const QString &jsonData)
{
    // qDebug() << "+++++";

    // 解析JSON数据
    QJsonDocument jsonDoc = QJsonDocument::fromJson(jsonData.toUtf8());
    QJsonObject jsonObj = jsonDoc.object();

    // Modbus配置信息
    QJsonObject modbusJson;
    QJsonArray modbusInfo;

    QString cliNum = jsonObj["cliNum"].toString();
    QString fileName = jsonObj["fileName"].toString() + "_" + cliNum;
    QString protocolType = jsonObj["protocolType"].toString();
    int _modbusSlaveId = jsonObj["slaveId"].toInt();
    int _modbusFunCode = jsonObj["funCode"].toInt();

    QString protocolTitle;
    modbusJson["ChanCode"] = cliNum;
    modbusJson["ChanDesc"] = "";
    modbusJson["ChanType"] = "7";
    if(protocolType == "TCP")
    {
        modbusJson["DataProtocol"] = "6";
        protocolTitle = "NetModTcp";
    }
    else if(protocolType == "RTU")
    {
        modbusJson["DataProtocol"] = "2";
        protocolTitle = "RTU";
    }
    modbusJson["WayUid"] = "1575876387";

    QString topicKeyValue;

    QJsonArray dataArray = jsonObj["modbusInfo"].toArray();
    for(const QJsonValue& value : dataArray)
    {
        QJsonObject _dataObj;

        int _addrBegin = value["addrBegin"].toString().toInt();
        int _addrEnd = value["addrEnd"].toString().toInt();
        int _opePointType = value["opePointType"].toInt();
        int _opePointCoeffi = value["opePointCoeffi"].toInt();


        int dataLen = _addrEnd - _addrBegin + 1;
        _dataObj["DataLen"] = QString::number(dataLen);
        _dataObj["DevName"] = "1301";
        _dataObj["FunCode"] = QString::number(_modbusFunCode);
        _dataObj["RegisterBegin"] = value["addrBegin"].toString();
        _dataObj["SlaveId"] = QString::number(_modbusSlaveId);

        QJsonArray _dataArray;
        for(int index = _addrBegin; index <= _addrEnd; index++)
        {
            QJsonObject _subObj;
            if(_opePointType == 0) // 数字量：按Bit位取值
            {
                for(int k = 1; k <= 16; k++)
                {
                    float _bitAddr = float(index) + (float)k / 100;

                    int int_Alias = qRound(_bitAddr * (float)100);
                    // int(_bitAddr * (float)100)
                    QString _alias = QString::number(int_Alias);

                    topicKeyValue += _alias;
                    topicKeyValue += ",";

                    _subObj["Addr"] = QString::number(_bitAddr, 'f', 2);
                    _subObj["Alias"] = _alias;

                    _subObj["Coefficient"] = OperatePointCoefficient(_opePointCoeffi);

                    _subObj["DataLen"] = "1";
                    _subObj["DataTypeRegister"] = QString::number(OperatePointType(_opePointType));

                    _dataArray.append(_subObj);
                }
            }
            else if(_opePointType == 3 || _opePointType == 4 || _opePointType == 5) // 浮点型数据
            {
                QString _alias = QString::number(index * 100);
                topicKeyValue += _alias;
                topicKeyValue += ",";

                _subObj["Addr"] = QString::number(index);
                _subObj["Alias"] = _alias;

                _subObj["Coefficient"] = OperatePointCoefficient(_opePointCoeffi);

                _subObj["DataLen"] = "2";
                _subObj["DataTypeRegister"] = QString::number(OperatePointType(_opePointType));

                _dataArray.append(_subObj);
                index = index + 1;
            }
            else
            {
                QString _alias = QString::number(index * 100);
                topicKeyValue += _alias;
                topicKeyValue += ",";

                _subObj["Addr"] = QString::number(index);
                _subObj["Alias"] = _alias;

                _subObj["Coefficient"] = OperatePointCoefficient(_opePointCoeffi);

                _subObj["DataLen"] = "1";
                _subObj["DataTypeRegister"] = QString::number(OperatePointType(_opePointType));

                _dataArray.append(_subObj);
            }
        }

        _dataObj["Results"] = _dataArray;

        modbusInfo.append(_dataObj);
    }

    modbusJson[protocolTitle] = modbusInfo;


    QFile tmpFile("debug.json");
    if (tmpFile.open(QIODevice::WriteOnly))
    {
        // 将JSON数据写入文件
        tmpFile.write(jsonDoc.toJson());
        tmpFile.close();
    }

    QJsonDocument docModbusCnf(modbusJson);
    // 创建JSON文件
    QFile file("./modbus/" + fileName + ".json");
    if (file.open(QIODevice::WriteOnly))
    {
        // 将JSON数据写入文件
        file.write(docModbusCnf.toJson(QJsonDocument::Indented));
        file.close();
    }

    QFile topicFile("./modbus/" + fileName + ".txt");
    if (topicFile.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QTextStream stream(&topicFile);
        stream << topicKeyValue;

        topicFile.close();
    }
}
